using UniversalAdminSystem.Application.Authentication.DTOs;
using UniversalAdminSystem.Application.Authentication.Interfaces;
using UniversalAdminSystem.Domian.UserManagement.Aggregates;
using UniversalAdminSystem.Domian.UserManagement.IRepository;
using UniversalAdminSystem.Domian.UserManagement.ValueObj;
using UniversalAdminSystem.Application.UserManagement.Interface;
using UniversalAdminSystem.Domian.UserManagement.Entities;
using UniversalAdminSystem.Application.Common.Interfaces;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;

namespace UniversalAdminSystem.Application.Authentication.Service;

public class RegisterAppService : IRegisterAppService
{
    private readonly IUserRepository _userRepository;
    private readonly IPasswordHelper _passwordHelper;
    private readonly IUnitOfWork _unitOfWork;

    private readonly IRoleRepository _RoleRepo;

    public RegisterAppService(
        IUserRepository userRepository,
        IPasswordHelper passwordHelper,
        IUnitOfWork unitOfWork,
        IRoleRepository roleRepository)
    {
        _userRepository = userRepository;
        _passwordHelper = passwordHelper;
        _unitOfWork = unitOfWork;
        _RoleRepo = roleRepository;
    }

    public async Task<RegisterResultDto> RegisterAsync(RegisterDto dto)
    {
        try
        {
            // 开始事务
            await _unitOfWork.BeginTransactionAsync();

            // 检查账号是否已存在
            var existingUser = await _userRepository.GetUserByAccountAsync(dto.Account);
            if (existingUser != null)
            {
                throw new Exception("账号已存在");
            }

            // 检查邮箱是否已存在
            var existingUserByEmail = await _userRepository.GetUserByEmailAsync(dto.Email);
            if (existingUserByEmail != null)
            {
                throw new Exception("邮箱已被注册");
            }

            // 密码加密
            var (hashedPassword, salt) = _passwordHelper.HashPasswordWithSeparateSalt(dto.Password);

            // 创建用户信息
            var userInfo = UserInfo.CreateUserInfo();
            await _userRepository.AddUserInfoAsync(userInfo);
            var Role = await _RoleRepo.GetByNameAsync("普通用户") ?? throw new Exception("用户创建失败");
            // 创建用户
            var user = User.CreateUser(
                userInfo.UserInfoId,
                dto.Account,
                hashedPassword,
                dto.Email,
                salt,
                UserStatus.Normal,
                Role.RoleId.Value

            );

            await _userRepository.AddAsync(user);

            // 提交事务
            await _unitOfWork.CommitAsync();

            return new RegisterResultDto(
                user.UserId.Value.ToString(),
                user.Account.Value.ToString(),
                "注册成功"
            );
        }
        catch (Exception)
        {
            // 回滚事务
            await _unitOfWork.RollbackAsync();
            throw;
        }
    }
}